package com.example.demo6.Controller;

import com.example.demo6.utils.ServerResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@CrossOrigin
@RestController
public class CommomController {
    @Value("d:/upload")
    String uploadPath;

    @PostMapping("/upload")
    public ServerResponse<String> uploadFile(MultipartFile file) throws IOException {
        if(file.getSize()>0) {
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formatDate = currentDate.format(formatter);  //yyyy/MM/dd

            File path = new File(uploadPath, formatDate);
            if (!path.exists()) {
                path.mkdirs();
            }
            //取后缀  11111111111.mp3  newFileName新文件名称
            String newFileName = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //1.jpg--->
            File f = new File(path, newFileName);  //f就是我们上传的文件
            file.transferTo(f);
            return ServerResponse.createBySuccess(200, "upload/"+formatDate+"/"+newFileName, "上传成功");
        }else{
            return ServerResponse.createBySuccess(500,  "","上传失败");
        }
    }
}
